package com.xpgk.mvc.collection.bentryRegister;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.baseInfoSet.BaseInfoSet;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productPrice.ProductPrice;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.plugin.FileRenamePlugin;
import com.xpgk.tools.ToolDateTime;
import com.xpgk.tools.ToolSqlXml;

import net.sf.json.JSONObject;

@Service(name = CollectionBentryRegisterService.serviceName)
public class CollectionBentryRegisterService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(CollectionBentryRegisterService.class);
	public static final String serviceName = "collectionBentryRegisterService";

	/**
	 * 计算消费金额
	 * 
	 * @param delWeight
	 * @param productIds
	 * @return
	 */
	public RenderBean getCost(String tem, String productIds, String orgids) {
		double cost = 0;
		double tream = 1;
		String msg = "";
		RenderBean result = new RenderBean();
		Product p = Product.dao.findById(productIds);
		String dlcsql = getSqlMy(Product.sqlId_selProByIds);
		Product dlc = Product.dao.findFirst(dlcsql, productIds, orgids);
		if (dlc != null) {
			// 如果是单疗程
			if (p != null && p.getStr(Product.column_proUnits).equals(Code.dlc_units)) {
				// 查出产品价格
				// cost=680;

				if (dlc.getFloat(ProductPrice.column_outPrice) != null) {
					cost = dlc.getFloat(ProductPrice.column_outPrice);
				} else {
					msg = "疗程未设置价格！！";
				}
			}
			// 如果是一疗程
			else if (p != null && p.getStr(Product.column_proUnits).equals(Code.bzlc_units)
					&& p.getStr(Product.column_proCapacity).equals(Code.ylc_capacity)) {
				if (dlc.getFloat(ProductPrice.column_outPrice) != null) {
					cost = dlc.getFloat(ProductPrice.column_outPrice);
				} else {
					msg = "疗程未设置价格！！";
				}
			} else {
				if (!tem.equals("")) {

					// 查出产品价格
					cost = dlc.getFloat(ProductPrice.column_outPrice) * Integer.parseInt(tem);
					tream = Integer.parseInt(tem);
				} else {

					if (dlc.getFloat(ProductPrice.column_outPrice) != null) {
						cost = dlc.getFloat(ProductPrice.column_outPrice);
					} else {
						msg = "疗程未设置价格！！";
					}
				}
			}
		} else {
			msg = "疗程未设置价格！！";
		}

		result.setMsg(msg);
		result.getMap().put("cost", cost);
		result.getMap().put("tream", tream);
		return result;
	}

	/**
	 * 保存顾客登记信息
	 */
	public RenderBean saveCus(CollectionCustomer cus, CollectionCustomerDetail cusDet, CollectionCustomerAgreement cusAgr, String orgids) {
		RenderBean result = new RenderBean();
		String msg = "";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", CollectionCustomer.column_hybh);
		String sql = getSqlByBeetl(CollectionCustomer.sqlId_column, param);
		CollectionCustomer cc = CollectionCustomer.dao.findFirst(sql, cus.getStr(CollectionCustomer.column_hybh));
		if (cc != null) {
			cc.set(CollectionCustomer.column_sfzmhm, cus.getStr(CollectionCustomer.column_sfzmhm));
			if (!cc.update()) {
				log.debug("更新顾客信息失败");
				throw new RuntimeException("更新顾客信息失败!");
			}
			Map<String, Object> param1 = new HashMap<String, Object>();
			param1.put("column", CollectionCustomerDetail.column_customerIds);
			String sqldet = getSqlByBeetl(CollectionCustomerDetail.sqlId_column, param1);
			CollectionCustomerDetail cd = CollectionCustomerDetail.dao.findFirst(sqldet, cc.getStr(CollectionCustomer.column_ids));
			if (cd != null) {
						cd.set(CollectionCustomerDetail.column_birth, cusDet.getDate(CollectionCustomerDetail.column_birth))
						.set(CollectionCustomerDetail.column_job, cusDet.getStr(CollectionCustomerDetail.column_job))
						.set(CollectionCustomerDetail.column_provice, cusDet.getStr(CollectionCustomerDetail.column_provice))
						.set(CollectionCustomerDetail.column_city, cusDet.getStr(CollectionCustomerDetail.column_city))
						.set(CollectionCustomerDetail.column_area, cusDet.getStr(CollectionCustomerDetail.column_area))
						.set(CollectionCustomerDetail.column_address, cusDet.getStr(CollectionCustomerDetail.column_address))
						.set(CollectionCustomerDetail.column_chargePersion, cusDet.getStr(CollectionCustomerDetail.column_chargePersion))
						.set(CollectionCustomerDetail.column_customerType, 0);
						if(cusAgr.getStr(CollectionCustomerAgreement.column_codeIds) !=null &&cusAgr.getStr(CollectionCustomerAgreement.column_codeIds).equals("0")){
							cd.set(CollectionCustomerDetail.column_customerType, 1);//只塑性
						}
				if (!cd.update()) {
					log.debug("更新顾客详细信息失败");
					throw new RuntimeException("更新顾客详细信息失败!");
				}

			}
			msg = ConstantRender.render_success_code;
			result.getMap().put("customerIds", cc.getStr(CollectionCustomer.column_ids));
		} else {
			log.debug("根据会员编号没有查出顾客信息！顾客不存在！！");
			msg = "顾客不存在！";
		}
		result.getMap().put("msg", msg);
		return result;

	}

	/**
	 * 获取协议编号
	 * 
	 * @param tre(疗程数)
	 * @return 编号
	 */
	public static String getBH(String depBH, Integer treatment,String hybh,Date date) {
		// 获取当月
		SimpleDateFormat df = new SimpleDateFormat("yyMM");
		String date2 = df.format(date);
		// //获取当前代理商门店编号
		// String dlmdBH="1401001";
		String chybh = hybh.substring(2, hybh.length());
		String p =  depBH + date2 + String.format("%02d", treatment) + chybh;
		return p;



	}

	/**
	 * 上传正面照和侧面照
	 * 
	 * @param files
	 * @param cusIds
	 * @return
	 */
	public JSONObject imageUpload(List<UploadFile> files, String cusIds) {
		JSONObject json = new JSONObject();
		Map<String, String> nameMap = new HashMap<>();
		if (files != null && files.size() > 0) {
			for (int i = 0; i < files.size(); i++) {
				String uploadPath = files.get(i).getUploadPath();// 获取保存文件的文件夹
				String fileName = files.get(i).getFileName();// 获取保存文件的文件名
				String filePath = uploadPath + "/" + fileName;// 保存文件的路径
				String extension = fileName.substring(fileName.lastIndexOf("."));
				String fName = fileName.substring(0, fileName.lastIndexOf("."));
				String resultFileName = FileRenamePlugin.instance.changeFileName(uploadPath + "/" + fName, extension);// 为了避免相同文件上传冲突，使用工具类重新命名
				nameMap.put(files.get(i).getParameterName(), resultFileName);
				File source = new File(filePath);
				String savePath = Code.savePicture_path;
				System.out.println("============================================================="+extension);
				if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)
						|| "jpeg".equals(extension) || "bmp".equals(extension)) {
					try {
						FileInputStream fis = new FileInputStream(source);

						File targetDir = new File(savePath);
						if (!targetDir.exists()) {
							targetDir.mkdirs();
						}
						File target = new File(targetDir, fileName);
						if (!target.exists()) {
							target.createNewFile();
						}
						FileOutputStream fos = new FileOutputStream(target);
						byte[] bts = new byte[1024 * 20];
						while (fis.read(bts, 0, 1024 * 20) != -1) {
							fos.write(bts, 0, 1024 * 20);
						}
						fos.close();
						fis.close();
						json.put("status", 0);
						source.delete();

					} catch (FileNotFoundException e) {
						json.put("status", 1);
						json.put("message", "上传出现错误，请稍后再上传");
					} catch (IOException e) {
						json.put("status", 1);
						json.put("message", "文件写入服务器出现错误，请稍后再上传");
					}
				} else {
					source.delete();
					json.put("status", 1);
					json.put("message", "只允许上传png,jpg,jpeg,gif,bmp类型的图片文件");
				}
			}
		} else {
			json.put("status", 2);
			json.put("message", "顾客信息保存成功，未上传图片");
		}
		CollectionCustomer cus = CollectionCustomer.dao.findById(cusIds);
		if (cus != null) {
			cus.set(CollectionCustomer.column_zmPicture, nameMap.get("zmfile"))
					.set(CollectionCustomer.column_cmPicture, nameMap.get("cmfile")).update();
		}
		return json;
	}

	/**
	 * 根据顾客（会员）编号，手机号，姓名查出顾客信息
	 */
	public Map<String, Object> getCusByHybh(String hybh, String name, String phone, String orgid) {

		String msg = ConstantRender.render_success_code;
		if (hybh != null && !hybh.equals("")) {
			hybh = String.format("%06d", Integer.parseInt(hybh));
		}

		Map<String, Object> queryParam = new HashMap<String, Object>();
		queryParam.put("organIds", orgid);
		queryParam.put("hybh", hybh);
		queryParam.put("name", name);
		queryParam.put("phone", phone);

		List<Record> lis = find(CollectionCustomer.sqlId_selCus, queryParam);
		Map<String, Object> mm = new HashMap<>();
		if (lis != null && lis.size() > 0) {
			if (lis.size() > 1) {
				msg = "姓名重复，请用手机号或编号查询!";
				mm.put("customer", null);
			} else {
				CollectionCustomer  cus=CollectionCustomer.dao.findById(lis.get(0).get(CollectionCustomer.column_ids));
				
				String sql1 = " select  *  from sb_customer_service_partsize   where customerIds= ?  ORDER BY  createDate  DESC ";
				List<Record> sps = Db.find(sql1 , cus.get("ids"));
				Date gq= null;
				long days = -1;//第一次量体重
				if(sps!=null&&sps.size()>0){
					Record ps = sps.get(0);
					gq=ps.getDate("createDate");
					long diff = new Date().getTime() - gq.getTime();//这样得到的差值是微秒级别  
				    days = diff / (1000 * 60 * 60 * 24);  
				}
				
				
				long count = 15;
				

				if(days>=count||days==-1){
					mm.put("daysflag", "1");
					mm.put("days", days);
				}
				String sql2 = " select  *  from sb_customer_detail   where customerIds= ?   ";
				List<Record>  cdl = Db.find(sql2 , cus.get("ids"));
				Record r = cdl.get(0);
				SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-dd");
				r.set("toStoreDate",sdf.format(r.getDate("toStoreDate")) );
				r.set("minDate",sdf.format(r.getDate("minDate")) );
				mm.put("customerDetail", r);
				mm.put("customer", cus);
			}
		} else {
			msg = "会员不存在，请重新输入查询条件！";
		}
		mm.put("msg", msg);
		return mm;
	}

	// 根据机构id获取机构编号
	public static String getOrgBh(String orgIds) {
	Organization or = Organization.dao.findById(orgIds);
	if (or != null) {
	if (or.getStr(Organization.column_xzqh) != null) {
	String mdbh = String.format("%02d", or.getInt(Organization.column_mdbh));
	return or.getStr(Organization.column_xzqh) + mdbh;
	} else {
	return null;
	}

	} else {
	return null;
	}

	}



	/**
	 * 上一个下一个
	 * 
	 * @param hybh
	 * @param obj
	 * @param orgIds
	 * @return
	 */
	public CollectionCustomer selOther(String hybh, String obj, String orgIds) {
		CollectionCustomer cus = new CollectionCustomer();
		if (hybh != "") {
			int n = Integer.parseInt(hybh);
			if (obj != "") {
				if (obj.equals("1")) {
					log.debug("获取上一条数据");
					hybh = String.format("%06d", n - 1);
				}
				if (obj.equals("2")) {
					log.debug("获取下一条数据");
					hybh = String.format("%06d", n + 1);
				}
			}
			String sql = getSqlMy(CollectionCustomer.sqlId_selCusByHybhAndOrg);
			CollectionCustomer cc = CollectionCustomer.dao.findFirst(sql, hybh, orgIds);
			if (cc != null) {
				cus = cc;
			}else
			{
				cus=null;
			}
		} else {
			 if(obj.equals("1"))
			 {
				log.debug("获取上一条数据");
				Map<String, Object> param1 = new HashMap<String, Object>();
				param1.put("column", CollectionCustomer.column_organIds);
				String sql1 = getSqlByBeetl(CollectionCustomer.sqlId_column, param1);
				List<CollectionCustomer> ccList = CollectionCustomer.dao.find(sql1, orgIds);
				if (ccList != null && ccList.size() > 0) {
					cus = ccList.get(0);
				}
			 }else
			 {
					cus=null;
			 }
		}
		return cus;
	}

//	/**
//	 * 保存基础资料
//	 * 
//	 * @param controller
//	 * @return
//	 */
//	public RenderBean saveBaseInfo(Controller controller) {
//		RenderBean result = new RenderBean();
//		String customerIds = controller.getPara("customerID");
//		String sql1 = "select ids from sb_customer_baseInfo where customerIds = ?";
//		List<CustomerBaseInfo> cbis = CustomerBaseInfo.dao.find(sql1, customerIds);
//		if (cbis.size() > 0) {
//			for (CustomerBaseInfo csi : cbis) {
//				csi.delete();
//			}
//		}
//		String sql = ToolSqlXml.getSqlMy(BaseInfoSet.sqlId_child);
//		List<BaseInfoSet> titles = BaseInfoSet.dao.find(sql, BaseInfoSet.rootIds);
//		if (titles.size() > 0) {
//			for (BaseInfoSet title : titles) {
//
//				List<BaseInfoSet> items = BaseInfoSet.dao.find(sql, title.getPKValue());
//				if (items.size() > 0) {
//					for (BaseInfoSet item : items) {
//						String input_name = item.getStr(BaseInfoSet.column_input_name);
//						String parm_name = controller.getPara(input_name);
//						new CustomerBaseInfo().set(CustomerBaseInfo.column_customerIds, customerIds)
//								.set(CustomerBaseInfo.column_titleIds, title.getPKValue())
//								.set(CustomerBaseInfo.column_itemIds, item.getPKValue())
//								.set(CustomerBaseInfo.column_value, parm_name).save();
//					}
//				}
//
//			}
//		}
//		result.setCode(ConstantRender.render_success_code);
//		return result;
//	}
	/**
	 * 保存基础资料
	 * 
	 * @param controller
	 * @return
	 */
	public RenderBean saveBaseInfo(CollectionCustomerHabit customerHabit,String organIds,String userIds) {
		RenderBean result = new RenderBean();
		String  msg="";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", customerHabit.column_customerID);
		String sql = getSqlByBeetl(customerHabit.sqlId_column, param);
		CollectionCustomerHabit habit = CollectionCustomerHabit.dao.findFirst(sql,customerHabit.getStr(CollectionCustomerHabit.column_customerID));
		if (habit!=null) {
			habit.set(CollectionCustomerHabit.column_organIds, organIds);
			habit.set(CollectionCustomerHabit.column_updateId, userIds);
			
			habit.set(CollectionCustomerHabit.column_gxsj, ToolDateTime.getDate());
			if(habit.update()){
				msg=ConstantRender.render_success_code;
			}else{
				msg="修改失败";
			}
			result.getMap().put("msg", msg);
			return result;
		}else{
			String cusIds = customerHabit.getStr(CollectionCustomerHabit.column_customerID);
			
			
			if(cusIds == null ){
				msg = "顾客不能为空";
				result.getMap().put("msg", msg);
				return result;
			}else if(userIds == null){
				msg = "操作人员不能为空，请重新登录";
				result.getMap().put("msg", msg);
				return result;
			}
				else{
				customerHabit.set(CollectionCustomerHabit.column_organIds, organIds);
				customerHabit.set(CollectionCustomerHabit.column_serviceID, userIds);
				customerHabit.set(CollectionCustomerHabit.column_createDate, ToolDateTime.getDate());
				if(customerHabit.save()){
					
					System.out.println("添加成功");
					msg=ConstantRender.render_success_code;
				
				}else{
					System.out.println("shibai ");
					msg="添加失败！";
				}
				
				result.getMap().put("msg", msg);
				return result;
		}
		}
		}

	public List<CollectionCustomer> getCusInfo(String orgid) {
		String sql1 = "select * from sb_customer where organIds = ? and  dataStatus in ('1','2')";
		List<CollectionCustomer> cbis = CollectionCustomer.dao.find(sql1, orgid);
		return cbis;
	}

	public List<Record> getView(String cUserOrganIds) {
		String sql1 = "SELECT b.name,a.* "
					+"FROM"
					+"sb_customer_service a"
					+"LEFT JOIN  sb_customer_detail b"
					+"ON a.customerID = b.customerIds"
					+" WHERE a.endTime IS NULL AND  a.dataStatus in ('1','2')  AND a.organids =?  ORDER BY  a.createDate DESC";
		List<Record> cbis = Db.find(sql1, cUserOrganIds);
		return cbis;
	}

}
